from datetime import datetime

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session, Session
from sqlalchemy import Column, DateTime, Integer, MetaData, String, Table, func, INTEGER, DATETIME, select, or_, JSON
from sqlalchemy.dialects.mysql import TINYINT, VARCHAR

from utils.encrypt_helper import encrypt_util
from utils.token import TokenHandler

# 连接到SQLite数据库
db_engine = create_engine('sqlite:///db/a_plus_max.db')
base_metadata = MetaData()

# 注册 validate
username = input("名称: ")
password = input("密码 6到16位: ")
mobile = input("手机号: ")
roles = ["admin"]

users = Table(
    'users', base_metadata,
    Column('id', Integer, primary_key=True),
    Column('username', VARCHAR(20), nullable=False),
    Column('roles', VARCHAR(100)),
    Column('mobile', VARCHAR(20), nullable=False),
    Column('created_at', DateTime, nullable=False, default=func.now()),
    Column('deleted_at', DateTime),
    Column('password', VARCHAR(500), nullable=False, comment='$划分'),
    Column('updated_at', DateTime, default=func.now(), onupdate=func.now()),
    Column('gender', Integer, nullable=False, comment='0是女,1是男'),
    Column('birthday', DateTime)
)

default_birthday_string = "2023-10-01 12:17:00"
default_birthday = datetime.strptime(default_birthday_string, "%Y-%m-%d %H:%M:%S")
# 创建用户
user_info = {
    'username': str(username),
    "roles": ",".join(roles),
    'mobile': str(mobile),
    'password': encrypt_util.hash(str(password)),
    'gender': 1,
    'birthday': default_birthday,
}

session_factory = sessionmaker(bind=db_engine, autoflush=False, autocommit=False)
session_factory = scoped_session(session_factory)


def get_session() -> Session:
    """
    获取数据库连接
    """
    return session_factory()


db_session = lambda: get_session()

insert_stmt = users.insert().values(user_info)
result = db_session().execute(insert_stmt)
# 收到影响的行数
# inserted_rows = result.rowcount
db_session().commit()

token_handler = TokenHandler()
token = token_handler.gen_token(result.inserted_primary_key[0])
user_info["id"] = result.inserted_primary_key[0]

db_session().close()
print("创建完成")